/*******************************************************************************
 * Copyright (c) 2006 CEA List.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     CEA List - initial API and implementation
 *******************************************************************************/
package com.cea.papyrus.core.commands;

import org.eclipse.uml2.uml.Element;

import com.cea.papyrus.core.helper.IGraphElementHelper;
import com.cea.papyrus.core.utils.Debug;

/**
 * Generic command to create element in the model, with no information about current diagram.
 * 
 * @author Remi SCHNEKENBURGER
 */
public class UMLElementCreateCommand extends PapyrusCommand {
	
	/**
	 * Create element.
	 */
	private Element element;
	
	/**
	 * parent of the created element.
	 */
	private Element parent;
	
	/**
	 * Default Constructor.
	 * 
	 * @param elementClass the type of element to create
	 * @param parent the parent of the element to create
	 */
	public UMLElementCreateCommand(Class elementClass, Element parent) {
		super(elementClass);
		this.parent = parent;
		this.setLabel("\"Creation of "+ elementClass.getSimpleName()+"\"");
	}
	
	/* (non-Javadoc)
	 * @see org.eclipse.gef.commands.Command#execute()
	 */
	/**
	 * 
	 */
	public void execute() {
		Debug.debug(this, "execute "+getLabel(), channel);
		if(elementFactory instanceof IGraphElementHelper) {
			element=((IGraphElementHelper)elementFactory).createUMLElement( parent);
		}
	}
	
	/* (non-Javadoc)
	 * @see org.eclipse.gef.commands.Command#canExecute()
	 */
	/**
	 * 
	 * 
	 * @return 
	 */
	public boolean canExecute() {
		if ( (parent != element) && (elementFactory instanceof IGraphElementHelper) ) {
			return ((IGraphElementHelper)elementFactory).canCreateUMLElement(parent);
		}
		
		return false;
	}
	
	/* (non-Javadoc)
	 * @see org.eclipse.gef.commands.Command#canUndo()
	 */
	/**
	 * 
	 * 
	 * @return 
	 */
	public boolean canUndo() {
		return (elementFactory instanceof IGraphElementHelper);
	}
	
	/* (non-Javadoc)
	 * @see org.eclipse.gef.commands.Command#undo()
	 */
	/**
	 * 
	 */
	public void undo() {
		if(elementFactory instanceof IGraphElementHelper) {
			((IGraphElementHelper)elementFactory).removeUMLElement(element, parent);
		} 
	}
	
	/* (non-Javadoc)
	 * @see org.eclipse.gef.commands.Command#redo()
	 */
	/**
	 * 
	 */
	public void redo() {
		if(elementFactory instanceof IGraphElementHelper) {
			((IGraphElementHelper)elementFactory).addUMLElement(element, parent);
		}
	}

	/**
	 * Returns the created element or <code>null</code>.
	 * 
	 * @return the created element
	 */
	public Element getElement() {
		return this.element;
	}
}
